<template>
  <el-select
    v-model="selectedArr"
    multiple
    filterable
    :disabled="disabled"
    :loading="loading"
    :collapse-tags="collapseTags"
    placeholder="请选择"
    @change="changeSelect"
    @remove-tag="removeTag"
  >
    <el-option
      v-if="selectOptions.length"
      label="全选"
      value="全选"
      @click.native="selectAll"
    ></el-option>
    <el-option
      v-for="item in selectOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    ></el-option>
  </el-select>
</template>

<script setup lang="ts">
const props = defineProps({
  // 选项
  selectOptions: {
    type: Array as PropType<Array<SelectOption>>,
    default() {
      return [];
    }
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 已选中选项
  mulSelecteds: {
    type: Array<String>,
    default() {
      return [];
    }
  },
  loading: {
    type: Boolean,
    default: false
  },
  collapseTags: {
    type: Boolean,
    default: true
  }
});

const selectedArr = ref<String[]>(props.mulSelecteds);
const emit = defineEmits(["update:updateMultipleSelect"]);

watch(
  () => props.mulSelecteds,
  newVal => {
    selectedArr.value = newVal;
    if (
      !selectedArr.value.includes("全选") &&
      selectedArr.value.length &&
      selectedArr.value.length === props.selectOptions.length
    ) {
      selectedArr.value.unshift("全选");
    }
  },
  { immediate: true }
);

const selectAll = () => {
  if (selectedArr.value.length < props.selectOptions.length) {
    selectedArr.value = [];
    props.selectOptions.map(item => {
      selectedArr.value.push(item.value);
    });
    selectedArr.value.unshift("全选");
  } else {
    // 取消全选
    selectedArr.value = [];
  }
  emit("update:updateMultipleSelect", selectedArr.value);
};

const changeSelect = (val: string) => {
  if (!val.includes("全选") && val.length === props.selectOptions.length) {
    selectedArr.value.unshift("全选");
  } else if (val.includes("全选") && val.length - 1 < props.selectOptions.length) {
    selectedArr.value = selectedArr.value.filter(item => {
      return item !== "全选";
    });
  }
  emit("update:updateMultipleSelect", selectedArr.value);
};
const removeTag = (val: string) => {
  if (val === "全选") {
    selectedArr.value = [];
    emit("update:updateMultipleSelect", selectedArr.value);
  }
};
</script>
